package top.swle.austers.jwt;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JwtUtil {
    static final SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    static final long ttlMillis = 60*60*24*  1000;

    public static String createJwt(String username) {
        String secretString = Encoders.BASE64.encode(key.getEncoded());
        System.out.println("key="+secretString);

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        String jws = Jwts.builder()
                .setExpiration(new Date(nowMillis + ttlMillis))
                .setAudience(username)
                .claim("uid", UUID.randomUUID().toString())
                .signWith(key)
                .compact();
        return jws;
    }

    public static String getUserName(String token){
        Jws<Claims> jws;
        try {
            jws = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token);
            System.out.println("------");
            return jws.getBody().getAudience();
        }catch(JwtException ex){
            System.out.println("sgibia");
            return null;
        }
    }

    public static Jws<Claims> parseJWT(String token){
        Jws<Claims> jws;
        try {
            jws = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token);
            System.out.println("------");
            return jws;
        }catch(JwtException ex){
            System.out.println("shibai");
            return null;
        }
    }

    public static boolean verify(String token){
        return false;
    }
}
